const Koa = require('koa');
const router = require('koa-router')();
const bodyparser = require('koa-bodyparser');

const app = new Koa();

app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.URL} ${ctx.request.url}..............`);
    await next();
});
app.use(bodyparser());
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>hello, ${name}</h1>`;
})

router.get('/', async (ctx, next) => {
    ctx.response.body = `<h1>index</h1>
    <form action="/signin" method="post">
    <p>name:<input name="name" value="koa"></p>
    <p>password:<input name="password" type="password"></p>
    <p><input type="submit" value="Submit"></p>
    </form>`;
})

router.post('/signin', async (ctx, next) => {
    var name = ctx.request.body.name || '';
    var password = ctx.request.body.password || '';
    console.log(`signin with name ${name} passowrd ${password}.....`);
    if (name === 'koa' && password === '123456') {
        ctx.response.body = `<h1>hello ${name}</h1>`;
    } else {
        ctx.response.body = `<h1>log fail</h1>
        <p><a href="/">try again</a></p>`;
    }
})


app.use(router.routes());

app.listen(3000);
console.log('server is running........................');